import { _decorator, Button, Component, instantiate, Label, Node, ProgressBar, SpriteFrame, tween, utils, Vec2, Vec3 } from 'cc';
import { UIOpacity } from 'cc';
import { UIBase } from './UIBase';
import GameData from '../data/GameData';
import Utils from '../utils/Utils';
import { UIEnd } from './UIEnd';
import { AudioManager } from '../game/AudioManager';
import { StageItem } from './item/StageItem';
import { EventListener } from '../game/EventListener';
import { Events } from '../game/Events';
import { Orientation, UIManager } from './UIManager';
const { ccclass, property } = _decorator;

@ccclass('UIStage')
export class UIStage extends UIBase {
    static instance: UIStage = null;
    @property(Node) bgPanel: Node = null;
    @property(Node) emitPoint_left: Node = null;
    @property(Node) emitPoint_right: Node = null;
    @property({ type: [Node] }) emitItemList: Node[] = [];
    @property(UIEnd) uiEnd: UIEnd = null;
    @property(Node) lv1: Node = null!;
    @property(Node) lv2: Node = null!;
    @property(Node) lv3: Node = null!;
    @property(Button) btn_test: Button = null;

    @property(StageItem) stageItem_hov: StageItem = null;   // 横屏舞台item
    @property(StageItem) stageItem_ver: StageItem = null;   // 竖屏舞台item

    onLoad() {
        super.onLoad();
        UIStage.instance = this;
    }

    start() {
        this.btn_test.node.on(Button.EventType.CLICK, this.playAnim, this);
        this.initOrientationUI();
        EventListener.on(Events.OrientationChange, this.initOrientationUI, this);
    }

    private initOrientationUI() {
        const isportrait = UIManager.Instance.orientation === Orientation.Portrait;
        this.stageItem_hov.node.active = !isportrait;
        this.stageItem_ver.node.active = isportrait;
    }

    public onShow(): void {
        super.onShow();
        this.playAnim();
    }


    public playAnim() {
        this.bgPanel.children.forEach((node, index) => {
            node.active = index === GameData.currentMap;
        });

        console.log("播放舞台动画");
        this.scheduleOnce(() => {
            this.playEmitEffectBarrage(this.emitPoint_left, 0.1, 50);
            this.playEmitEffectBarrage(this.emitPoint_right, 0.1, 50);
            this.stageItem_hov.playAnim();
            this.stageItem_ver.playAnim();
            AudioManager.Instance.playChest();
            this.scheduleOnce(() => {
                this.uiEnd.node.active = true;
            }, 6);
        }, 1);

        this.playAudienceTween(this.lv1, 10, 2);
        this.playAudienceTween(this.lv2, 15, 3);
        this.playAudienceTween(this.lv3, 15, 3);
    }

    /** 观众层左右晃动动画 */
    private playAudienceTween(node: Node, offset: number, duration: number) {
        if (!node) return;
        const origin = node.position.clone();
        const left = origin.clone();
        left.x -= offset;
        const right = origin.clone();
        right.x += offset;
        // 无限左右循环晃动
        tween(node)
            .to(duration, { position: left }, { easing: 'sineInOut' })
            .to(duration, { position: right }, { easing: 'sineInOut' })
            .union()
            .repeatForever()
            .start();
    }

    /** 连续多次发射，支持间隔和总次数 */
    playEmitEffectBarrage(emitPoint: Node, interval: number, count: number) {
        let i = 0;
        const timer = () => {
            if (i < count) {
                this.playEmitEffect(emitPoint);
                i++;
                setTimeout(timer, interval * 1000);
            }
        };
        timer();
    }

    /** 播放发射特效 */
    playEmitEffect(emitPoint: Node,) {
        const beginPos = emitPoint.getPosition().clone();
        // 发射点  emitPoint_left 为起点 x轴 正负 100以内随机
        const randomX = beginPos.x + (Math.random() - 0.5) * 400;
        const randomY = beginPos.y + (Math.random() - 0.5) * 50;
        const randPoint = new Vec3(randomX, randomY, 0);

        // 随机创建一个发射物
        const randomIndex = Math.floor(Math.random() * this.emitItemList.length);
        const emitItem = instantiate(this.emitItemList[randomIndex]);
        emitItem.setParent(this.node);
        emitItem.setPosition(randPoint);
        emitItem.active = true;

        tween(emitItem)
            .by(1 + Math.random() * 0.5, { position: new Vec3(0, 300 + Math.random() * 200, 0) })
            .call(() => {
                hideTween.start();
            })
            .start();

        const uiOpacity = emitItem.getComponent(UIOpacity);
        const hideTween = tween(uiOpacity)
            .to(0.1, { opacity: 0 })
            .call(() => {
                emitItem.removeFromParent();
                emitItem.destroy();
            })
    }
}


